package com.htjc.uep.center.commons.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestUtil {

	private static Logger log = LoggerFactory.getLogger(RequestUtil.class);
	
//	public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
//		
//		final CountDownLatch begin = new CountDownLatch(1);
//		
//		
//		final ExecutorService exec = Executors.newFixedThreadPool(400);
//		
//		for (int i = 0; i < 1; i++) {
//			
//			Runnable run = new Runnable() {
//				
//				@Override
//				public void run() {
//					try {
//						
//						begin.await();
//						
////						for (int j = 0; j<1; j++) {
//							String url = "http://127.0.0.1:8080/jf_acct/acct/acctData";
//							
//							String param = "userName=yao_xh&userPwd=312";
//							
//							String param2 = "{"
////									+ "\"dealId\": \"b9f68f76e6dd4494864b0eda7f88edc0\","
//									+ "\"mechanismCode\": \"WSGW_33101\","
//									+ "\"accountCode\": \"JSZJ-000001\","
//									+ "\"acctDate\": \"20181107\","
////									+ "\"repertoryId\": \"20181107\","
////									+ "\"userId\": \"b9f68f76e6dd4494864b0eda7f88edc0\","
////									+ "\"phone\": \"18045022330\","
////									+ "\"score\": \"100032\","
////									+ "\"bpType\": \"0101\","
////									+ "\"sendTime\": \"2018/11/07 12:23:45\","
//									+ "\"sign\": \"321321231asdf\"}";
//							
//							System.out.println(sendPost(url, param2));
////						}
//						
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//					
//				}
//			};
//			exec.submit(run);
//			
//			
//		}
//		
//		begin.countDown();
//		exec.shutdown();
//		
////		String url = "http://192.168.1.206:8080/business/deductionPointApply";
////		String param = "{"
////				+ "\"businessId\": \"b9f68f76e6dd4494864b0eda7f88edc0\","
////				+ "\"sourceNo\": \"02\","
////				+ "\"repertoryId\": \"00001\","
////				+ "\"repertoryName\": \"国网网上国网积分池\","
////				+ "\"mechanismCode\": \"WSGW-000001\","
////				+ "\"operator\": \"网上国网操作员1号\","
////				+ "\"operatorType\": \"0201\","
////				+ "\"operatorNum\": 100000,"
////				+ "\"remark\": \"申请网上国网合作平台\"}";
////		
////		String param1 = "{"
////				+ "\"mechanismCode\": \"WSGW-000001\","
////				+ "\"accountCode\": \"WSGW-000001\","
////				+ "\"score\": \"10000\","
////				+ "\"dealId\": \"b9f68f76e6dd4494864b0eda7f88edc0\"}";
////		
////		String param2 = "{"
////				+ "\"dealId\": \"b9f68f76e6dd4494864b0eda7f88edc0\","
////				+ "\"mechanismCode\": \"WSGW-33101\","
////				+ "\"accountCode\": \"JSZJ-000001\","
////				+ "\"acctDate\": \"20181107\","
////				+ "\"userId\": \"b9f68f76e6dd4494864b0eda7f88edc0\","
////				+ "\"phone\": \"18045022330\","
////				+ "\"score\": \"100032\","
////				+ "\"bpType\": \"0101\","
////				+ "\"sendTime\": \"2018/11/07 12:23:45\","
////				+ "\"sign\": \"321321231asdf\"}";
////		
////		RSAPublicKey publicKey = RSAUtil.getPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFfIzUKJmP5HFt3p5EQGqlysPXvXtcziwqdqBaet6FXrY9mwBKC-TcjyGmWsx1aFeM7zl8ywruvyQrOd_7SKWlbUZJCaNAqXVxjo8rFB0uAmhSW0-b8QEqNXU4hKIyifgzfgI5iUTR6VnPy48kvIXwDHX_wLl5PfZwb4oLUJnrFQIDAQAB-DN-AjmJRNHpWc_LjyS8hfAMdf_AuXk99nBvigtQmesVAgMBAAECgYBou5xTKbeyqm5E4hITQudqRXj7YHPWEP2eI40U8Kp-wh0CoQbNEh_y3Wptd3hL9h4bOedE_poJUHc0YyhVpF4yFv_ZAx0aZnoEZRyiGBxL1VINZpIF5r2NXYGNunemwaTs44PZpBs5wCbz6Gpdr4XcTu5RuT7U2OqlEDTv2cWVgQJBAMDPgC7IVeKmi0A32w1_ZRanCLyO3p7xKlVZKYga-jnR4-fJgEipmYJxGKX0Hb64lUxp-rwFVrM7pSsjDZhKgB0CQQCxO9uUYyoByuwgGDpGjLftBSmOBxMwEj_TSkOKXy-ViHn2Z5OYKm-HOgaWtU3MN62wmaXUXlpiG1RN2glWJRVZAkEAvBXvKjPdrFLgxk12j601tKpO2Hnaa1xA-q8W16HRdTPtyf-D994SVO_0pncDyTgQ1FER-faPRBqsHe985JHQdQJAFCvu4uWia0_QLhrzzwHHETfsMdkGSwtYrlCefUo2HTvKPcwuFTyHMwncpByAfUS9BQOHxzLx8IaRwsaVF3PjCQJAVfiLBMyHIGbMDcZZVmrVz-Didgkkw4aSTUnGRLFZB5YOp95IN_p4AUl-39gKcYRVXfrymFH7gWUci-cWUgedFA");
////		
////		String entPublicKey = RSAUtil.publicEncrypt(param1, publicKey);
////		
////		System.out.println(sendPost(url, param2));
//	}
	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
    	
    	OutputStreamWriter out = null;
    	InputStream is = null;
    	ByteArrayOutputStream bos = null;
        String result = "";
        try {
        	// 打开和URL之间的连接
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setReadTimeout(300000);
            conn.setConnectTimeout(10000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置编码格式
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json");
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
            out.write(param);
            out.flush();
            
            is = conn.getInputStream();
            bos = new ByteArrayOutputStream();
            int len = -1;
            byte[] by = new byte[1024];
            while((len = is.read(by)) != -1)
            {
            	bos.write(by, 0, len);
            }
            
            result = bos.toString("UTF-8");
            
        } catch (Exception e) {
        	log.error("发送 POST 请求出现异常！目标url={}", url + "/" + param, e);
            e.printStackTrace();
        }
        finally{
            IOUtil.closeQuietly(out, is, bos);
        }
        return result;
    }    
}
